package util;

import java.io.IOException;
import java.io.InputStream;

import javax.sql.DataSource;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import Interceptor.LogInterceptor;
import mapper.PersonMapper;
import pojo.Person;

/**
 * MybatisUtil
 */
public class MybatisUtil {

    private static SqlSessionFactory factory = null;
    private static SqlSessionFactory factory1 = null;

    static {
        InitMybatisByCode();
        InitMybatisByConfig();
    }

    /**
     * 代码创建 SqlSessionFactory
     */
    public static void InitMybatisByCode() {
        try {
            // 数据库连接池信息
            PooledDataSource dataSource = new PooledDataSource();
            dataSource.setDriver("org.sqlite.JDBC");
            // dataSource.setUsername("root");
            // dataSource.setPassword("1128");
            String dbPath = "MybatisSample/src/resources/mybatis.db";
            dataSource.setUrl("jdbc:sqlite:" + dbPath);
            dataSource.setDefaultAutoCommit(false);
            dataSource.setPoolMaximumActiveConnections(15);// 在任意时间可存在的活动（正在使用）连接数量，默认值：10

            // 采用 MyBatis 的 JDBC 事务方式
            TransactionFactory transactionFactory = new JdbcTransactionFactory();
            Environment environment = new Environment("development", transactionFactory, dataSource);

            // 创建 Configuration 对象
            Configuration configuration = new Configuration(environment);

            // 加入一个映射器
            configuration.addMapper(PersonMapper.class);

            // 使用 SqlSessionFactoryBuilder 构建 SqlSessionFactory
            factory = new SqlSessionFactoryBuilder().build(configuration);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * XML 构建 SqlSessionFactory
     */
    private static void InitMybatisByConfig() {
        try {
            String resource = "resources/mybatis-config.xml";
            // 加载MyBatis的主配置文件
            InputStream inputStream = Resources.getResourceAsStream(resource);
            // 通过构建器（SqlSessionFactoryBuilder）构建一个SqlSessionFactory工厂对象
            factory1 = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession() throws IOException {
        return factory.openSession();
    }

    public static SqlSession getSqlSessionByConfig() throws IOException {
        return factory1.openSession();
    }
}